package cn.xfdzx.android.apps.shop.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.MapLoactionAdapter;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.LocationInfo;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.evenbus.HomeAdressMessage;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

/**
 * @author gzk
 * @data 2020/03/27
 * 地图展示
 */
public class MoreAddressMapActivity extends BaseMvpActivity implements LocationSource, AMapLocationListener, AMap.OnCameraChangeListener, PoiSearch.OnPoiSearchListener {


    @BindView(R.id.map_confirm_address)
    MapView map;
    @BindView(R.id.ll_confirm_address_search)
    LinearLayout llConfirmAddressSearch;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    AMap aMap;//初始化地图控制器对象
    MyLocationStyle myLocationStyle;  //定位蓝点


    //定位需要的数据
    LocationSource.OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    @BindView(R.id.rv_confirm_address)
    RecyclerView mapRv;
    private List<LocationInfo> list = new ArrayList<>();
    private MapLoactionAdapter mapLoactionAdapter;
    private Marker mLocMarker;

    private PoiSearch search;
    private RelativeLayout.LayoutParams item_bar;
    private String pageForm="";//判断是否是首页跳转
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        map.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = map.getMap();
        }
        //设置地图的放缩级别
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        // 设置定位监听
        aMap.setLocationSource(this);

        aMap.setCustomMapStyle(
                new com.amap.api.maps.model.CustomMapStyleOptions()
                        .setEnable(true)
                        .setStyleId("3b7df2aeffe4f90411241e09282a2cfa")//官网控制台-自定义样式 获取
        );
        //蓝点初始化
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.getUiSettings().setZoomControlsEnabled(false);//设置默认定位按钮是否显示，非必需设置。
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次
        aMap.setOnCameraChangeListener(this);
        myLocationStyle.showMyLocation(true);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_more_address_map;
    }

    @Override
    public void initView() {
        initHigh();
        pageForm = getIntent().getStringExtra("pageForm")==null?"":getIntent().getStringExtra("pageForm");
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mapRv.setLayoutManager(linearLayoutManager);
        mapLoactionAdapter = new MapLoactionAdapter(list, this);
        mapRv.setAdapter(mapLoactionAdapter);
        mapLoactionAdapter.setOnItemClickListener(new  ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (EmptyUtil.isNotEmpty(pageForm)){
                    EventBus.getDefault().post(new HomeAdressMessage(list.get(position).getTitle(),list.get(position).getLatitude()+"",
                            list.get(position).getLonTitude()+""));
                    Intent intent = new Intent(MoreAddressMapActivity.this, MainActivity.class);
                    intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                    intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }else {
                    Intent intent=new Intent();
                    intent.putExtra("address_name",list.get(position).getAddress());
                    intent.putExtra("lontitude",list.get(position).getLonTitude()+"");
                    intent.putExtra("latitude",list.get(position).getLatitude()+"");
                    intent.putExtra("district",list.get(position).getDistrict()+"");
                    intent.putExtra("city",list.get(position).getCity()+"");
                    setResult(RESULT_OK,intent);
                }
                finish();
            }
        });


    }
    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @OnClick({R.id.iv_back, R.id.ll_confirm_address_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_confirm_address_search:
                //点击搜索框跳转
                Intent intent_search = new Intent(this, SearchAddressActivity.class);
                intent_search.putExtra("pageForm",pageForm);
                startActivityForResult(intent_search,START_CODE);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        map.onPause();
        if (mlocationClient != null) {
            //停止定位后，本地定位服务并不会被销毁
            mlocationClient.stopLocation();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }


    //--定位监听---------

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(getApplicationContext());
            //初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);

            //不允许模拟定位
            mLocationOption.setMockEnable(true);
            //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
            mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            if (null != mlocationClient) {
                mlocationClient.setLocationOption(mLocationOption);
                //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                mlocationClient.stopLocation();
                mlocationClient.startLocation();
            }
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //获取最近3s内精度最高的一次定位结果：
            mLocationOption.setOnceLocationLatest(true);
            //给定位客户端对象设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            //启动定位
            mlocationClient.startLocation();
        }

    }


    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    //定位回调  在回调方法中调用“mListener.onLocationChanged(amapLocation);”可以在地图上显示系统小蓝点。
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {

                nearLocation(aMapLocation);
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                addMarkerInScreenCenter();

            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("定位AmapErr", errText);
            }
        }
    }

    private void addMarkerInScreenCenter() {
        if (mLocMarker == null) {
            mLocMarker = aMap.addMarker(new MarkerOptions().zIndex(1));
        }
        mLocMarker.setAnchor(0.5f, 1.0f);
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        mLocMarker.setPositionByPixels(screenPosition.x, screenPosition.y);

    }


    @Override
    protected void onDestroy() {
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        map.onDestroy();
        super.onDestroy();

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        LatLng latLng = cameraPosition.target;
        if (mLocMarker != null) {
            mLocMarker.setPosition(latLng);
        }

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng target = cameraPosition.target;
        search.setBound(new PoiSearch.SearchBound(new LatLonPoint(target.latitude,
                target.longitude), 200));//设置周边搜索的中心点以及半径

        search.searchPOIAsyn();
    }




    private void nearLocation(AMapLocation aMapLocation) {

        double latitude = aMapLocation.getLatitude();//获取纬度
        double longitude = aMapLocation.getLongitude();//获取经度

        //不设置POI的类别，默认返回“餐饮服务”、“商务住宅”、“生活服务”这三种类别的POI
        PoiSearch.Query query = new PoiSearch.Query("", "", aMapLocation.getCity());
        query.setPageSize(20);
        query.setPageNum(1);
         search = new PoiSearch(this, query);
        search.setOnPoiSearchListener(this);
        search.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                longitude), 200));//设置周边搜索的中心点以及半径

        search.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        list.clear();
        ArrayList<PoiItem> pois = poiResult.getPois();
        for (PoiItem poi : pois) {

            LocationInfo info = new LocationInfo();
            LatLonPoint point = poi.getLatLonPoint();

            info.setTitle(poi.getTitle());
            info.setAddress(poi.getSnippet());
            info.setLatitude(point.getLatitude());
            info.setLonTitude(point.getLongitude());
            info.setCity(poi.getCityName());
            info.setDistrict(poi.getAdName());

            list.add(info);

            Log.i("名称", poi.getTitle());
            Log.i("详细地址", info.getAddress());
            Log.i("哪个区", info.getDistrict()+"");
            Log.i("哪个市", info.getCity()+"");
        }
        mapLoactionAdapter.setList(list);
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CODE) {
                Intent intent=new Intent();
                intent.putExtra("address_name",data.getStringExtra("address_name"));
                intent.putExtra("lontitude",data.getStringExtra("lontitude")+"");
                intent.putExtra("latitude",data.getStringExtra("latitude")+"");
                intent.putExtra("district",data.getStringExtra("district")+"");
                intent.putExtra("city",data.getStringExtra("city")+"");
                setResult(RESULT_OK,intent);
                finish();
            }
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }
}
